/* cl.ext.fileinput 0.1*/
(
    function (factory) {
        if (typeof define === 'function' && define.amd) {
            define(['jquery',"FileInput"], factory);
        } else if (typeof module === 'object' && module.exports) {
            module.exports = function( root, jQuery ) {
                var fileInputjs = require('FileInput');
                if ( jQuery === undefined ) {
                    if ( typeof window !== 'undefined' ) {
                        jQuery = require('jquery');
                    }
                    else {
                        jQuery = require('jquery')(root);
                    }
                }
                factory(jQuery);
                return jQuery;
            };
        } else {
            factory(jQuery);
        }
    }(
    function ($){
        var defaultExtInfo={"filetype":"jpg,png"};
        var defaults={
            initShowType:"previewFile", //previewFile| buttonFile
            "style": "well",
            "btn_change": null,
            "no_icon": 'ace-icon fa fa-picture-o',
            "allowExt": ["jpeg", "jpg", "png"],
            "allowMime": ["image/jpg", "image/jpeg", "image/png"],
            "droppable": true,
            "thumbnail": "fit",
            "whType":"equal",
            "showFileName": false,
            "beforeRemoveCallback":null,
            "checkCallback":null,
            "ajaxInfoCallback":null,
            "tipmsg_top":"",
            "tipmsg_bottom":"",
            "maxSize":false,
            "imgSrcUrl":false,
            "sizeWidth":0,
            "sizeHeight":0,
            "spanWidth":0,
            "infoExt":defaultExtInfo
        };
        var defaultsMime={
            "jpg":["image/jpg","image/jpeg","image/pjpeg"],
            "jpe":["image/jpg","image/jpeg","image/pjpeg"],
            "jpeg":["image/jpg","image/jpeg","image/pjpeg"],
            "png":["image/png","image/x-png"],
            "gif":["image/gif"],
            "bmp":["image/bmp"],
            "ico":["image/x-icon"],
            "mp3":["audio/mpeg"],
            "mid":["audio/midi"],
            "ogg":["audio/ogg"],
            "mp4a":["audio/mp4"],
            "wav":["audio/wav"],
            "wma":["audio/x-ms-wma"],
            "3gp":["video/3gpp"],
            "avi":["video/x-msvideo"],
            "asf":["video/x-ms-asf"],
            "dv":["video/x-dv"],
            "mov":["video/quicktime"],
            "mp4":["video/mp4"],
            "mpg4":["video/mp4"],
            "mpeg":["video/mpeg"],
            "mpg":["video/mpeg"],
            "ra":["audio/x-pn-realaudio"],
            "ram":["audio/x-pn-realaudio"],
            "rmvb":["video/vnd.rn-realvideo"],
            "wm":["video/x-ms-wmv"],
            "wmv":["audio/x-ms-wmv"],
            "wmx":["video/x-ms-wmx"],
            "flv":["video/x-flv"],
            "mkv":["video/x-matroska"],
            "txt":["text/plain"]
        };
        var defaultsSuffix={
            "jpg":["jpg","jpe","jpeg"],
            "png":["png"],
            "gif":["gif"],
            "bmp":["bmp"],
            "ico":["ico"],
            "mp3":["mp3"],
            "mid":["mid"],
            "ogg":["ogg"],
            "mp4a":["mp4a"],
            "wav":["wav"],
            "wma":["wma"],
            "3gp":["3gp"],
            "avi":["avi"],
            "asf":["asf"],
            "dv":["dv"],
            "mov":["mov"],
            "mp4":["mp4"],
            "mpg4":["mpg4"],
            "mpeg":["mpeg"],
            "mpg":["mpg"],
            "ra":["ra"],
            "ram":["ram"],
            "rmvb":["rmvb"],
            "wm":["wm"],
            "wmv":["wmv"],
            "wmx":["wmx"],
            "flv":["flv"],
            "mkv":["mkv"],
            "txt":["txt"]
        };
        var defaultsImg=["jpg","jpe","jpeg","png","gif","bmp","ico"];
        var $modalCommon={
            getDefaults :function () {
                return defaults
            },
            getOptions : function (elementData,options) {
                var self=this;
                options=$.ExtCommon.isCheckEmpty(options)?{}:options;
                var optionBase =$.ExtCommon.initMergeJson(elementData,options);
                optionBase =$.ExtCommon.initMergeJson(this.getDefaults(),optionBase);
                optionBase.maxSize=$.ExtCommon.isCheckEmpty(optionBase.maxSize)?false:optionBase.maxSize;
                optionBase.imgSrcUrl=$.ExtCommon.isCheckEmpty(optionBase.imgSrcUrl)?false:optionBase.imgSrcUrl;
                var fileImgType=self.getImgType(optionBase.infoExt.filetype);
                optionBase.isImgType=fileImgType.length>0;
                optionBase.infoExt.filetype=optionBase.isImgType?fileImgType.join(","):optionBase.infoExt.filetype;
                optionBase.no_icon=optionBase.isImgType? 'ace-icon fa fa-picture-o':'ace-icon fa fa-cloud-upload';
                optionBase.allowExt=self.getAllowExt(optionBase.infoExt.filetype);
                optionBase.allowMime=self.getAllowMime(optionBase.allowExt);
                optionBase.isImgType=optionBase.initShowType=="buttonFile"?false:optionBase.isImgType;
                if(optionBase.beforeRemoveCallback){
                    optionBase.before_remove=function(obj){
                        if(optionBase.beforeRemoveCallback){optionBase.beforeRemoveCallback(obj)}
                        return true
                    };
                }
                if(optionBase.ajaxInfoCallback){
                    var ajaxUrl=optionBase.ajaxInfoCallback.url;
                    var ajaxPara=$.ExtCommon.isCheckEmpty(optionBase.ajaxInfoCallback.data)?{}:{width:optionBase.ajaxInfoCallback.data.width,height:optionBase.ajaxInfoCallback.data.height};
                    if(optionBase.isImgType){
                        optionBase.ajaxCallback= function (file, imgbase64, cb) {
                            var para={imageStr: imgbase64};
                            if(!$.ExtCommon.isCheckEmpty(ajaxPara)){
                                para =$.ExtCommon.initMergeJson(ajaxPara,para);
                            }
                            $.ExtAjax.initPost({
                                url: ajaxUrl,
                                contentType: "application/x-www-form-urlencoded",
                                data: para,
                                successCallback: function (res) {
                                    if (res.success) {
                                        if(optionBase.ajaxInfoCallback.success){
                                            var aa=optionBase.ajaxInfoCallback.success(file.$element,res.data)
                                        }
                                        if (cb) cb();
                                    } else {
                                        $.ExtNotify.error(res.msg);
                                    }
                                }
                            });
                        }
                    }else{
                        optionBase.ajaxCallback= function (selfFile, filedata, cb) {
                            var formData = new FormData();
                            if(filedata.length){
                                for(var f=0;f<filedata.length;f++){
                                    formData.append("file["+f+"]",filedata[f]);
                                }
                            }else{
                                formData.append("file",filedata);
                            }
                            $.ExtAjax.initPost({
                                url: ajaxUrl,
                                data: formData,
                                cache: false,
                                processData: false,
                                contentType: false,
                                successCallback: function (res) {
                                    if (res.success) {
                                        if(optionBase.ajaxInfoCallback.success){
                                            var aa=optionBase.ajaxInfoCallback.success(selfFile.$element,res.data)
                                        }
                                        if (cb) cb();
                                    } else {
                                        $.ExtNotify.error(res.msg);
                                    }
                                }
                            });
                        }
                    }
                }
                if($.ExtCommon.isCheckEmpty(optionBase.checkCallback)) {
                    optionBase.checkCallback = function (obj, err) {
                        if (err.length > 0) {
                            $.ExtNotify.error(err.join("<br />"));
                        }
                    };
                }
                return optionBase
            },
            getImgType:function(type){
                var arrType=type.split(",");
                return $.map(arrType,function(info,i){if(defaultsImg.indexOf(info)>-1){return info;}});
            },
            getAllowExt:function(type){
                var arr=type.split(",");
                var arrExt=$.map(arr,function(info,i){return defaultsSuffix[info]?defaultsSuffix[info]:[]});
                return $.ExtCommon.getArrUnique(arrExt)
            },
            getAllowMime:function(ext){
                var arrMime=$.map(ext,function(info,i){return defaultsMime[info]?defaultsMime[info]:[]});
                return $.ExtCommon.getArrUnique(arrMime)
            },
            getButtonFileHtml:function(){
                return '<button  class="btn btn-customf5 waves-effect btn-file" type="button">'+
                    '<i class="fa fa-cloud-upload m-r-5"></i><span>上传文件</span>'+
                    '</button>';
            }
        };
        var modalOperateElement=function(element,options){
            this.$element =element;
            this.optionModal=options;
        };
        modalOperateElement.prototype = {
            init: function () {
                this.bindEvent();
            },
            bindEvent:function(){
                var self=this;
                self.$element.off("change").on("change", function(){
                    if( self.optionModal.ajaxCallback){
                        self.optionModal.ajaxCallback(self,this.files)
                    }
                });
            },
            destroyHtml:function(){
                this.$element.parent().empty().remove();
                this.$element=null;
            }
        };
        var UploadFileExtModal = function(element, options) {
            var self=this;
            self.element = $(element);
            self.optionBase=$modalCommon.getOptions(self.element.data(),options);
            switch(self.optionBase.initShowType){
                case "previewFile":
                    self.element.ace_file_input(self.optionBase);
                    break;
                case "buttonFile":
                    var p=$($modalCommon.getButtonFileHtml());
                    self.element.before(p);
                    self.element.appendTo(p);
                    self.elementOperate=new modalOperateElement(this.element,this.optionBase);
                    self.elementOperate.init();
                    break;

            }
        };
        UploadFileExtModal.prototype = {
            init:function(){},
            destroy:function(){}
        };
        $.fn.ExtUploadFile = function(options) {
            var dataFun;
            this.each(function() {
                var el = $(this);
                var tempData=el.data('ExtUploadFile');
                if (tempData) {
                    if (typeof  options == "string") {
                        if (tempData[options]) {
                            dataFun =tempData[options]()
                        } else {
                            dataFun = tempData
                        }
                    } else {
                        dataFun = tempData
                    }
                } else {
                    dataFun = new UploadFileExtModal(el, options);
                    el.data('ExtUploadFile', dataFun);
                }
            });
            return dataFun;
        };
        return UploadFileExtModal;
    })
);
